<template>
  <VPage>
    <template #left>
      <div class="left">
        <el-tree
          :data="departmentList"
          :props="defaultProps"
          @node-click="handleNodeClick"
          highlight-current
          :expand-on-click-node="false"
          node-key="id"
          class="department_tree"
          :default-expanded-keys="[2]"
        >
          <template #default="{ node }">
            <span class="custom_tree_node">
              <el-tooltip
                v-if="node.label.length >= 9"
                class="item"
                effect="dark"
                :content="node.label"
                placement="top_start"
              >
                <span class="lable">{{ node.label }}</span>
              </el-tooltip>
              <span class="lable" v-else>{{ node.label }}</span>
            </span>
          </template>
        </el-tree>
      </div>
    </template>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="创建时间" value="create_time"></el-option>
            <el-option label="修改时间" value="update_time"></el-option>
          </el-select>
          <el-date-picker
            v-model="form.dateRange.value"
            type="datetimerange"
            range-separator="至"
            start-placeholder="00:00:00"
            end-placeholder="23:59:59"
            style="width: 400px"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime"
          />
        </VGroup>
        <el-input
          v-model="form.en_name"
          placeholder="英文名"
          prefix-icon="search"
          @keyup.enter.native="refresh"
          clearable
          style="width: 160px"
        />
        <el-input
          v-model="form.realname"
          placeholder="真实姓名"
          prefix-icon="search"
          @keyup.enter.native="refresh"
          clearable
          style="width: 160px"
        />
        <el-input
          v-model="form.mobile"
          placeholder="手机号"
          prefix-icon="search"
          @keyup.enter.native="refresh"
          clearable
          style="width: 160px"
        />
        <el-select
          v-model="form.job_status"
          placeholder="在职状态"
          clearable
          style="width: 90px"
        >
          <el-option
            v-for="item in jobType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="form.status"
          placeholder="账号状态"
          clearable
          style="width: 100px"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="form.account_type"
          placeholder="账号类型"
          clearable
          style="width: 100px"
        >
          <el-option
            v-for="item in accountType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </template>
      <template #toolbar_btns>
        <el-button
          type="primary"
          @click="handleAdd(null)"
          v-hasPermi="[personnelAuthList.user.add]"
          ><SvgIcon
            icon-class="Plus"
            class="text-[12px] mr-[6px]"
          />新增</el-button
        >
        <el-dropdown trigger="click" @command="batchOptionsEvent">
          <el-button type="primary">
            批量操作<SvgIcon
              icon-class="ArrowDown"
              class="text-[12px] ml-[4px]"
            />
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <template v-for="item in batchList" :key="item">
                <template v-if="isPermission(item?.permission)">
                  <el-dropdown-item :command="item.label">{{
                    item.value
                  }}</el-dropdown-item>
                </template>
              </template>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button
          class="ml-auto"
          @click="handleSync"
          v-hasPermi="[personnelAuthList.user.async]"
          ><SvgIcon
            icon-class="Refresh"
            class="text-[12px] mr-[6px]"
          />同步飞书</el-button
        >
        <el-button
          @click="handleAccount"
          v-hasPermi="[personnelAuthList.user.disable_account]"
          ><SvgIcon
            icon-class="Setting"
            class="text-[12px] mr-[6px]"
          />自动禁用账号设置</el-button
        >
      </template>
      <template #userName="{ row }">
        <div>
          <div class="flex items-center">
            <span
              :class="row.job_status_text === '在职' ? 'ustatus' : 'unstatus'"
              >{{ row.job_status_text }}</span
            >
            <span
              :class="row.job_status_text === '在职' ? 'text-[#3d8eff]' : ''"
              ><svg-icon
                :icon-class="row.is_department_head ? 'guanli' : 'yuangong'"
                style="fontsize: 16px"
              ></svg-icon
            ></span>
            <span>{{ row.en_name }}({{ row.realname }})</span>
          </div>
          <div class="text-[#666] text-[12px]">{{ row.office }}</div>
        </div>
      </template>
      <template #loginlook="{ row }">
        <template v-if="row?.login_ip !== '--'">
          <el-button link type="primary" @click="handleLoginlook(row.user_id)"
            >{{ row?.login_ip }} 查看</el-button
          >
        </template>
        <template v-else>
          {{ row?.login_ip }}
        </template>
      </template>
      <template #operation="{ row }">
        <div>
          <el-button
            link
            type="primary"
            @click="handleAdd(row.id)"
            v-hasPermi="[personnelAuthList.user.edit]"
            >编辑</el-button
          >

          <el-button
            link
            type="primary"
            @click="handleAuthNew(row.id)"
            v-hasPermi="[personnelAuthList.user.adjust_permissions_new]"
            >权限调整</el-button
          >

          <el-button
            link
            type="primary"
            @click="handlePermission(row.user_id)"
            v-hasPermi="[personnelAuthList.user.data_permissions]"
            >数据权限分布</el-button
          >
          <el-button link type="primary" @click="handleLog(row.id)"
            >日志</el-button
          >
          <div>
            <el-button
              link
              type="primary"
              @click="handleAuth(row.id)"
              v-hasPermi="[personnelAuthList.user.adjust_permissions]"
              >权限调整</el-button
            >
          </div>
        </div>
      </template>
    </VTable>
  </VPage>
  <ViewMac
    v-model="viewMacVisible"
    :data="viewMacData"
    :id="viewMacId"
    @refresh="refresh"
    @close="viewMacData = []"
  />
  <Add
    v-model="addVisible"
    :id="addId"
    :menuList="departmentList"
    :title="addTitle"
    @refresh="refresh"
    @close="addId = ''"
  ></Add>
  <SetAccount
    v-model="accountVisible"
    :day="accountDay"
    @refresh="refresh"
    @close="accountDay = 0"
  />
  <EditDepartments
    v-model="deptVisible"
    :menuList="departmentList"
    :ids="visibleId"
    @refresh="refresh"
    @close="visibleId = []"
  />
  <AddMac
    v-model="addMacVisible"
    :ids="visibleId"
    @refresh="refresh"
    @close="visibleId = []"
  />
  <BatchValidate
    v-model="validateVisible"
    :ids="visibleId"
    :title="validateTitle"
    :type="validateType"
    @refresh="refresh"
    @close="(visibleId = []), (validateType = 0)"
  />
  <BatchLink
    v-model="BatchLinkVisible"
    :ids="visibleId"
    @refresh="refresh"
    @close="visibleId = []"
  />
  <EditRole v-model="authVisible" :id="authId" @close="authId = null" />
  <EditRoleNew
    v-model="authVisibleNew"
    :id="authIdNew"
    @close="authIdNew = null"
  />

  <PermissionDistribution
    ref="permissionDistribution"
    :formData="permissionData"
  />
  <AuthorizationXy
    v-model="AuthorizationXyVisible"
    :ids="visibleId"
    @refresh="refresh"
    @close="visibleId = []"
  />
  <CopyUser
    v-model="copyUserVisible"
    :ids="visibleId"
    @refresh="refresh"
    @close="visibleId = []"
  />
  <VLog ref="roleLog" :api="api.userOplog"></VLog>
  <Loginlook
    v-model="LoginlookVisible"
    :id="LoginlookUser"
    @close="LoginlookUser = null"
  ></Loginlook>
</template>
<script setup lang="jsx">
import SvgIcon from "@/components/SvgIcon/index.vue";
import { ElMessage } from "element-plus";
import { copyText } from "@/utils/tools.js";
import Add from "./component/add/index.vue";
import ViewMac from "./component/viewMac/index";
import SetAccount from "./component/setAccount/index";
import EditDepartments from "./component/editDepartments/index";
import AddMac from "./component/addMac/index";
import BatchLink from "./component/batchLink/index";
import BatchValidate from "./component/batchValidate/index";
import EditRole from "./component/editRole/index.vue";
import EditRoleNew from "./component/editRole/indexNew.vue";
import PermissionDistribution from "./component/permissionDistribution";
import AuthorizationXy from "./component/authorizationXy/index";
import VLog from "@/components/VLog";
import Loginlook from "./component/Loginlook/index";
import api from "./api";
import {
  defaultProps,
  defaultTime,
  statusOptions,
  accountType,
  jobType,
  batchList,
} from "./data.js";
import { personnelAuthList } from "@/Auth/personnel.js";
import { isPermission } from "@/hooks/permission.js";
import CopyUser from "./component/CopyUser/index";
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      job_status: 1,
      dateRange: { type: "create_time", value: [], range: true }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    contentMethod: ({ column, row }) => {
      const { field } = column;
      if (field === "role_name") {
        if (row?.roles && Array.isArray(row.roles)) {
          return row.roles.map((role) => role.role_name).join("，");
        }
        return "";
      }
    },
  },
  isToggle: true,
  columns: [
    { type: "checkbox", width: "40", fixed: "left" },
    { field: "id", title: "ID", width: "60", fixed: "left" },
    {
      field: "name",
      title: "名字",
      width: "200",
      fixed: "left",
      slots: { default: "userName" },
    },
    {
      field: "role_name",
      title: "角色",
      width: "200",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.roles.map((e) => {
                return (
                  <el-tag class="ml-2" type="info">
                    {e.role_name}
                  </el-tag>
                );
              })}
            </div>
          );
        },
      },
    },
    { field: "mobile", title: "手机号码", width: "200" },
    { field: "employee_no", title: "工号", width: "200" },
    { field: "birthday", title: "生日", width: "200" },
    {
      field: "status",
      title: "账号状态",
      width: "100",
      slots: {
        default: ({ row }) => {
          return <VstatusRender label={row.status_text} value={row.status} />;
        },
      },
    },
    {
      field: "xy_oauth_status",
      title: "跨境兴运授权状态",
      width: "150",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.xy_oauth_status == 0 ? (
                <div>未授权</div>
              ) : row.xy_oauth_status == 1 ? (
                <div>已启用</div>
              ) : (
                <div>已禁用</div>
              )}
            </div>
          );
        },
      },
    },
    { field: "account_type_text", title: "账号类型", width: "100" },
    {
      field: "is_verify_elink",
      title: "专属链接",
      width: "120",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-tag type="primary" onClick={() => copyText(row.elink)}>
                点击复制
              </el-tag>
            </div>
          );
        },
      },
    },
    {
      field: "mac",
      title: "MAC链接",
      width: "100",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-button
                type="info"
                plain
                size="small"
                onClick={() => viewMacLink(row)}
              >
                查看
              </el-button>
            </div>
          );
        },
      },
    },
    { field: "create_time", title: "创建时间", width: "200" },
    {
      field: "login_ip",
      title: "登陆IP",
      width: "200",
      slots: { default: "loginlook" },
    },
    { field: "last_login_time", title: "最后登录时间", width: "200" },
    {
      field: "update_user_text",
      title: "修改人",
      width: "200",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText value={row.update_user_text} />
              <VText value={row.update_time} />
            </div>
          );
        },
      },
    },
    {
      title: "操作",
      width: "280",
      fixed: "right",
      slots: {
        default: "operation",
      },
    },
  ],
  proxyConfig: {
    seq: true,
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return api.userList({ ...form, ...page });
      },
    },
  },
});
//获取部门树
const departmentList = ref([]);
const getDepartment = async (type) => {
  const { data } = await api.department({ type });
  departmentList.value = data || [];
};
getDepartment(1);

//选中部门树
const handleNodeClick = (data) => {
  nextTick(() => {
    tableRef?.value.setFormField("department_id", data.id);
    refresh();
  });
};

//mac链接
const viewMacVisible = ref(false);
const viewMacData = ref([]);
const viewMacId = ref(null);
const viewMacLink = (val) => {
  viewMacData.value = val?.mac || [];
  viewMacId.value = val?.id;
  viewMacVisible.value = true;
};

//编辑
const addTitle = ref("新增");
const addVisible = ref(false);
const addId = ref("");
const handleAdd = (id) => {
  addId.value = id || null;
  addVisible.value = true;
  addTitle.value = id ? "编辑" : "新增";
};
//同步员工信息
const handleSync = async () => {
  const { code, message } = await api.syncFeishu();
  if (code != 200) return ElMessage.error(message);
  ElMessage.success("同步成功！");
  refresh();
};
//自动禁用账号设置
const accountVisible = ref(false);
const accountDay = ref(0);
const handleAccount = async () => {
  const { data } = await api.getDisableAccount();
  accountDay.value = data?.day_in_not_login || 0;
  accountVisible.value = true;
};
//日志
const roleLog = ref();
const handleLog = (id) => {
  roleLog.value.open(id);
};

//登录IP
const LoginlookVisible = ref(false);
const LoginlookUser = ref(null);
const handleLoginlook = (val) => {
  LoginlookUser.value = val;
  LoginlookVisible.value = true;
};

const deptVisible = ref(false);
const addMacVisible = ref(false);
const visibleId = ref([]);
const validateTitle = ref("");
const validateVisible = ref(false);
const validateType = ref(0);
const BatchLinkVisible = ref(false);
const AuthorizationXyVisible = ref(false);
const copyUserVisible = ref(false);
const batchOptionsEvent = (e) => {
  const records = tableRef.value?.$table.getCheckboxRecords();

  if (!records?.length) {
    return ElMessage.warning("请至少选择一条数据!");
  }

  const ids = records.map((item) => item.id);
  visibleId.value = ids;

  // 定义各操作的处理函数
  const actions = {
    1: () => {
      deptVisible.value = true;
    },
    2: () => {
      if (ids.length > 1) {
        return ElMessage.warning("最多只能选择一条数据!");
      }
      addMacVisible.value = true;
    },
    3: () => {
      validateTitle.value = "是否验证设备MAC地址";
      validateType.value = 1;
      validateVisible.value = true;
    },
    4: () => {
      validateTitle.value = "是否验证专属链接";
      validateType.value = 2;
      validateVisible.value = true;
    },
    5: () => {
      validateTitle.value = "是否允许账号密码登录";
      validateType.value = 3;
      validateVisible.value = true;
    },
    6: () => {
      const userIds = records.map((item) => item.user_id);
      visibleId.value = userIds;
      BatchLinkVisible.value = true;
    },
    7: () => {
      AuthorizationXyVisible.value = true;
    },
    8: () => {
      copyUserVisible.value = true;
    },
  };

  // 执行对应的处理函数
  actions[e]?.();
};
//权限调整
const authId = ref(null);
const authVisible = ref(false);
const handleAuth = (id) => {
  authId.value = id;
  authVisible.value = true;
};

const authIdNew = ref(null);
const authVisibleNew = ref(false);
const handleAuthNew = (id) => {
  authIdNew.value = id;
  authVisibleNew.value = true;
};

//数据权限分布
const permissionData = ref({});
const permissionDistribution = ref();
const handlePermission = async (user_id) => {
  const { data } = await api.getAccessData({ user_id });
  permissionData.value = data;
  permissionDistribution.value.open();
};
//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
</script>
<style scoped lang="scss">
.department_tree {
  width: 100%;
  margin-top: 5px;

  &:deep(.el-tree-node) {
    margin: 12px 0;
  }
  .custom_tree_node {
    display: flex;
    justify-content: space-between;
    vertical-align: middle;
    width: 100%;
    span {
      align-self: center;
    }
    .lable {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  &:deep(.el-tree-node__content) {
    padding-right: 10px;
  }
}
:deep(
    .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content
  ) {
  background-color: transparent;

  .lable {
    color: #3487ff !important;
  }
}

.ustatus {
  color: #faad14;
  background-color: var(--base-warning-bg);
  font-size: 12px;
  padding: 0 5px;
  border-radius: 3px;
}

.unstatus {
  color: var(--base-sub-text-color);
  background-color: var(--base-border-color);
  padding: 0 5px;
  font-size: 12px;
  border-radius: 3px;
}
:deep(.el-tag.el-tag--primary) {
  background-color: var(--base-primary-bg);
  border-color: var(--base-primary-bg);
}
</style>
